<template>
    <nly-content-wrapper style="overflow-x:hidden;">
        <nly-content-header>

            <section>
                <div class="big-main-wrapper" style="border-bottom:0px;margin:0px;padding-bottom: 5px;">
                    <div class="btn-wrapper clearfix" style="border-bottom:0px;">
                        <a-row class="text-center clearfix">
                            <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                                <a-col v-if="permissions.includes('role:add')" :span="2">
                                    <div class="btns" @click="AddRole">
                                        <a-icon class="btns-icon" type="file-add" />
                                        <div class="btns-text" title="添加">添加</div>
                                    </div>
                                </a-col>
                                <a-col v-if="permissions.includes('role:edit')" :span="2">
                                    <div class="btns" @click="showModal">
                                        <a-icon class="btns-icon" type="edit" />
                                        <div class="btns-text" title="修改">修改</div>
                                    </div>
                                </a-col>
                                <a-col v-if="permissions.includes('role:enable')" :span="2">
                                    <div class="btns" @click="updateRole">
                                        <a-icon class="btns-icon" type="retweet" />
                                        <div class="btns-text" title="启用">启用/停用</div>
                                    </div>
                                </a-col>

                                <a-col v-if="permissions.includes('role:delete')" :span="2">
                                    <div class="btns" @click="deleteSysRole">
                                        <a-icon class="btns-icon" type="delete" />
                                        <div class="btns-text" title="删除">删除</div>
                                    </div>
                                </a-col>

                            </a-col>
                        </a-row>
                    </div>
                </div>
            </section>

            <!-- <nly-row class="col-12">
                <nly-row class="col-12 ">
                    <nly-col xs="12" sm="12" md="12" lg="9" xl="9" class="form-inline" style="justify-content: left;">
                    </nly-col>
                    <nly-col xs="12" sm="12" md="12" lg="3" xl="3" class="form-inline align-self-start" style="justify-content: right;">
                        <nly-button-group>
                            <nly-button variant="info" @click="PageListRole" button-class="mr-2">查询</nly-button>
                            <nly-button variant="info" button-class="mr-2" @click="reset">重置</nly-button>
                            <nly-button @click="showFunction" variant="info" button-class="mr-2">
                                <nly-icon :icon="show ? 'fas fa-angle-down mr-1' : 'fas fa-angle-up mr-1'" />
                                {{ show ? "折叠" : "展开" }}
                            </nly-button>
                        </nly-button-group>
                    </nly-col>
                </nly-row>

                <nly-row class="ml-1 mb-2 lr mt-4" v-show="show">
                    <nly-col xs="12" sm="12" md="12" lg="12" xl="12" class="form-inline" style="justify-content: left;">
                        <form-input name="name" title="角色名称" id="name" labelStyle rightStyle="width:120px;" class="ml-2" v-show="show" v-model="postData.roleName"></form-input>
                        <div style="margin-left: 20px;">状态：</div>
                        <a-select default-value style="width: 120px" @change="handleChange">
                            <a-select-option value>全部</a-select-option>
                            <a-select-option value="0">正常</a-select-option>
                            <a-select-option value="2">停用</a-select-option>
                        </a-select>
                    </nly-col>
                </nly-row>
            </nly-row> -->
        </nly-content-header>
        <!-- <nly-button-group style="margin-left: 30px;margin-bottom: 10px;display:initial" v-if="permissions.includes('role:add')">
            <a-button type="primary" class="crm-btn" @click="AddRole" button-class="mr-2">添加角色</a-button>
        </nly-button-group> -->
        <nly-content>
            <!-- 列表 -->
            <a-table :columns="columns" :data-source="data" bordered :pagination="pagination" :row-selection="rowSelection" style="font-size: 12px;" @change="onTableChange" :scroll="{ x: 1000, y: 500 }">
                <template slot="treeSort" slot-scope="text, record">
                    <editable-cell :text="text" @editableChange="onCellChange(record,'treeSort',$event)" :reg="numberReg" />
                </template>
            </a-table>
            <!-- modal角色编辑 弹窗  -->
            <a-modal class="edit-class" v-model="editModal" centered :title="editItem.id ? '编辑角色' : '新增角色'" width="900px" @cancel="hideModal">
                <div id="components-form-demo-advanced-search">
                    <a-form class="ant-advanced-search-form" :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 24 }" @submit="handleSubmit">
                        <div class="line" style="color:#1980Ff;font-size:15px;">基本信息</div>
                        <a-row :gutter="24">
                            <a-col :span="10">
                                <a-form-item label="角色名称">
                                    <a-input v-decorator="['roleName', { rules: [{ required: true, message: '角色名称不能为空' }] }]" placeholder="请输入角色名称" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="10" :push="2">
                                <a-form-item label="排序号">
                                    <a-input v-decorator="['roleSort', { rules: [{ required: false, message: '排序号不能为空' }] }]" placeholder="根据排序号从小到大排序" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="10">
                                <a-form-item label="用户类型">
                                    <a-select v-decorator="['userType', { rules: [{ required: false, message: '' }] }]" placeholder="请选择用户类型">
                                        <a-select-option value="1">员工</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="10" :push="2">
                                <a-form-item label="角色分类">
                                    <a-select v-decorator="['roleType', { rules: [{ required: false, message: '' }] }]" placeholder="请选择角色分类">
                                        <a-select-option value="1">高管</a-select-option>
                                        <a-select-option value="2">中层</a-select-option>
                                        <a-select-option value="3">基层</a-select-option>
                                        <a-select-option value="4">其他</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="22" :pull="3">
                                <a-form-item label="角色描述">
                                    <a-textarea placeholder="请输入角色描述" :rows="1" v-decorator="['remarks', { rules: [{ required: false, message: '' }] }]" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <div class="line" style="color:#1980Ff;font-size:15px;">授权功能菜单</div>
                        <div style="overflow: auto; overflow-x:hidden;">
                            <a-row :gutter="24">
                                <!-- <a-col :offset="2">
                                    <a-tree :checkedKeys="checkedKeys" checkable :expanded-keys="expandedKeys" :auto-expand-parent="autoExpandParent" :selected-keys="selectedKeys" :tree-data="treeData" @expand="onExpand" @select="onSelect" @check="onCheck" :show-line="true" />
                                </a-col> -->
                                <a-tabs v-if="treeData.length > 0" @change="callback" v-model="currentItemId">
                                    <a-tab-pane :key="item.id" :tab="item.menuName" v-for="item in treeData" :forceRender="true">
                                        <div style="width:96%;margin-left:10px;height:300px;overflow-y:auto">
                                            <a-tree :checkedKeys="treeDataCheckedMap.get(currentItemId) || []" checkable :expanded-keys="expandedKeysMap.get(currentItemId) || []" :auto-expand-parent="autoExpandParent" :tree-data="treeData.filter(res=>{return item.id == res.id})" @expand="onExpand" @check="onCheck" :show-line="true" />
                                            <!-- <a-table :columns="tableTreeColumns" :data-source="treeData.filter(res=>{return item.id == res.id})" :row-selection="{onSelect:onSelect,onChange:onCheck}" :expanded-row-keys.sync="expandedKeys" bordered :pagination="false">

                                            </a-table> -->
                                        </div>
                                    </a-tab-pane>
                                </a-tabs>
                            </a-row>
                        </div>
                        <div class="line" style="color:#1980Ff;font-size:15px;margin-top:20px;">查询范围</div>
                        <a-row :gutter="24">
                            <a-col :offset="2">
                                <a-radio-group button-style="solid" v-model="dataScope" class="btn-group-fa">
                                    <a-radio-button value="1"><i class="fa fa-user" />
                                        <p>本人数据</p>
                                    </a-radio-button>
                                    <a-radio-button value="2"><i class="fa fa-users" />
                                        <p>部门数据</p>
                                    </a-radio-button>
                                    <a-radio-button value="3"><i class="fa fa-building" />
                                        <p>公司数据</p>
                                    </a-radio-button>
                                    <a-radio-button @click="showOfficeModal(1)" value="4"><i class="fa fa-users" />
                                        <p>跨部门数据</p>
                                    </a-radio-button>
                                    <a-radio-button @click="showOfficeModal(2)" value="5"><i class="fa fa-cog" />
                                        <p>自定义人员</p>
                                    </a-radio-button>
                                </a-radio-group>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
                <template slot="footer">
                    <a-button type="primary" html-type="submit" @click="handleSubmit">保存</a-button>
                    <a-button :style="{ marginLeft: '8px' }" @click="handleReset">重置</a-button>
                    <a-button :style="{ marginLeft: '8px' }" @click="hideModal">关闭</a-button>
                </template>
            </a-modal>
            <a-modal :visible="officeModal" :footer="null" :title="editItem.type==1 ? '部门选择' : '用户选择'" size="sm" @cancel="hideOfficeModal">
                <div style="height: 400px;overflow-y:scroll;">
                    <a-tree v-model="checkedOfficeKeys" checkable :expanded-keys="expandedOfficeKeys" :tree-data="officeTreeData" @expand="onOfficeExpand" @check="onOfficeCheck" :show-line="true" />
                </div>
                <a-row>
                    <a-col :span="24" :style="{ textAlign: 'right' }">
                        <a-button type="primary" html-type="submit" @click="hideOfficeModal">确认</a-button>
                        <a-button :style="{ marginLeft: '8px' }" @click="hideOfficeModal">关闭</a-button>
                    </a-col>
                </a-row>
            </a-modal>
        </nly-content>
    </nly-content-wrapper>
</template>

<script>

import { mapState } from "vuex";
import { FormInput, EditableCell } from "@/components/Form";
import { PageListRole, saveSysRole, deleteSysRole, MenuList } from "@/api/role";
import { TreeDataOffice, OfficeList } from "@/api/office";
import { adminMenu } from "@/api/menu";
import { constantRouterComponentsKeys } from "@/router/generator-routers";

/**
 * 菜单数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const listToTree = (list, childrenNav, parentId) => {
    list.forEach(item => {
        // 判断是否为父级菜单
        if (item.parentId === parentId) {
            let key = item.id;
            const child = {
                ...item,
                title: item.menuName,
                key: key,
                children: []
            };
            // 迭代 list， 找到当前菜单相符合的所有子菜单
            listToTree(list, child.children, item.id);
            // 删掉不存在 children 值的属性
            if (child.children.length <= 0) {
                delete child.children;
            }
            // 加入到树中
            childrenNav.push(child);
        }
    });
};

/**
 * 机构数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const officeListToTree = (list, childrenOffice, parentId) => {
    list.forEach(item => {
        // 判断是否为父级菜单
        if (item.parentId == parentId) {
            const child = {
                ...item,
                title: item.name,
                key: item.id,
                children: []
            };
            // 迭代 list， 找到当前菜单相符合的所有子菜单
            officeListToTree(list, child.children, item.id);
            // 删掉不存在 children 值的属性
            if (child.children.length <= 0) {
                delete child.children;
            }
            // 加入到树中
            childrenOffice.push(child);
        }
    });
};

export default {
    components: {
        FormInput,
        EditableCell
    },
    data () {
        const columns = [
            {
                title: "角色名称",
                dataIndex: "roleName",
                key: "roleName",
                width: "120"
            },
            {
                title: "系统角色",
                dataIndex: "isSys",
                key: "isSys",
                width: "120",
                customRender: (text, row, index) => {
                    return text == true ? "是" : "否";
                }
            },
            {
                title: "数据范围",
                dataIndex: "dataScope",
                key: "dataScope",
                width: "120",
                customRender: (text, row, index) => {
                    let dataArr = [
                        "本人数据",
                        "部门数据",
                        "公司数据",
                        "跨部门数据",
                        "自定义人员"
                    ];
                    return dataArr[text - 1];
                }
            },
            {
                title: "角色分类",
                dataIndex: "roleType",
                key: "roleType",
                width: "120",
                customRender: (text, row, index) => {
                    const roleType = ["", "高管", "中层", "基层", "其他"];
                    return roleType[text];
                }
            },
            {
                title: "用户类型",
                dataIndex: "userType",
                key: "userType",
                width: "120",
                customRender: (text, row, index) => {
                    const userType = ["", "员工", "会员"];
                    return userType[text];
                }
            },
            {
                title: "排序号",
                dataIndex: "roleSort",
                key: "roleSort",
                width: "120"
            },
            {
                title: "状态",
                dataIndex: "status",
                key: "status",
                width: "120",
                customRender: (text, row, index) => {
                    return text == 2 ? (
                        <nly-badge bg-variant="danger">停用</nly-badge>
                    ) : (
                        <nly-badge bg-variant="success">正常</nly-badge>
                    );
                }
            },
            // {
            //     title: "操作",
            //     dataIndex: "o",
            //     width: "200",
            //     key: "o",
            //     customRender: (text, row, index) => {
            //         const { permissions } = this;
            //         if (row.id != 1)
            //             return (
            //                 <div class="icons-list">
            //                     {permissions.includes('role:edit') ? <a
            //                         href="javascript:;"
            //                         title="编辑角色"
            //                         class="mr-1"
            //                         onClick={() => this.showModal(row)}
            //                     >
            //                         <a-icon type="edit" theme="twoTone" />
            //                     </a> : null}

            //                     {permissions.includes('role:enable') && row.status == 2 ? (
            //                         <a
            //                             href="javascript:;"
            //                             title="启用角色"
            //                             class="mr-1 "
            //                             onClick={() => this.updateRole(row)}
            //                         >
            //                             <a-icon
            //                                 type="check-circle"
            //                                 theme="twoTone"
            //                                 two-tone-color="#52c41a"
            //                             />
            //                         </a>
            //                     ) : (permissions.includes('role:enable') ?
            //                         <a
            //                             href="javascript:;"
            //                             title="禁用角色"
            //                             class="mr-1 "
            //                             onClick={() => this.updateRole(row)}
            //                         >
            //                             <a-icon type="stop" theme="twoTone" two-tone-color="red" />
            //                         </a> : null
            //                     )}
            //                     {permissions.includes('role:delete') ? <a
            //                         href="javascript:;"
            //                         title="删除角色"
            //                         class="mr-1 "
            //                         onClick={() => this.deleteSysRole(row)}
            //                     >
            //                         <a-icon
            //                             type="delete"
            //                             theme="twoTone"
            //                             two-tone-color="#eb2f96"
            //                         />
            //                     </a> : null}

            //                 </div>
            //             );
            //     }
            // }
        ];

        const treeData = [];
        const officeTreeData = [];

        return {
            tableKeys: [],
            tableRows: [],
            showTabTree: true,
            currentItemId: null,
            treeDataCheckedMap: new Map(),
            expandedKeysMap: new Map(),
            halfCheckedKeysMap: new Map(),
            autoExpandParent: true,
            expandedKeys: [],
            checkedKeys: [], //tree默认选中的key
            selectedKeys: [],
            expandedOfficeKeys: [],
            checkedOfficeKeys: [], //office tree默认选中的key
            selectedOfficeKeys: [],
            halfCheckedKeys: [],
            dataScope: "1",
            treeData,
            officeTreeData,
            form: this.$form.createForm(this, { name: "advanced_search" }),
            formLayout: "horizontal",
            expand: false,
            editModal: false,
            postData: {
                "page.current": 1,
                "page.size": 20,
                roleName: "",
                status: ""
            },
            numberReg: /^[1-9]{1}[0-9]*$/,
            floatReg: /^-?[0-9]*(\.[0-9]*)?$/,
            data: [],
            columns,
            pagination: {
                defaultPageSize: 20,
                current: 1,
                pageSize: 20,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input-number
                                value={this.pagination.pageSize}
                                min={1}
                                max={500}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                // showSizeChanger: true,
                showQuickJumper: true,
                showLessItems: true
                // pageSizeOptions: ["10", "20", "30", "40", "50"]
            },
            show: false, //是否显示弹窗
            editItem: {}, //新增/编辑对象
            moduleList: [], //所有模块
            TreeSortEditList: new Map(), //菜单排序修改集合
            officeModal:false,


            //table树权限
            tableTreeColumns: [
                {
                    title: '菜单名称',
                    dataIndex: 'menuName',
                    key: 'menuName',
                    width: 100,
                },
                {
                    title: '权限',
                    dataIndex: 'permission',
                    key: 'permission',
                    width: 120,
                },
            ],
            nowBoxTop: 0,
            permissionTabsKey: 1,
        };
    },
    mounted () {
        this.PageListRole();
    },
    computed: {
        parentMenu: function () {
            const map = new Map();
            map.set(this.editItem.parentId, "");
            return map;
        },
        componentSelectList: function () {
            const dataList = new Array();
            constantRouterComponentsKeys().forEach(item => {
                dataList.push({ key: item, title: item });
            });
            return dataList;
        },
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),
        rowSelection () {
            return {
                selectedRowKeys: this.tableKeys,
                onChange: (selectedRowKeys, selectedRows) => {
                    this.tableKeys = selectedRowKeys;
                    this.tableRows = selectedRows;
                    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
                },
                columnWidth: 40,
            }
        },
    },
    methods: {
        changePageSize (e) {
            const value = e.target.value;
            const { pagination } = this;

            console.log(e, value);
            Object.assign(this.postData, {
                "page.size": value
            });
            Object.assign(this.pagination, {
                pageSize: Number.parseInt(value)
            });
            this.PageListRole();
        },
        hideModal () {
            this.editModal = false;
        },
        hideOfficeModal () {
            this.officeModal = false;
        },
        //添加
        AddRole () {
            this.tableKeys = [];
            this.tableRows = [];

            // this.expandedKeys = [];
            // this.checkedKeys = [];
            // this.halfCheckedKeys = [];
            this.expandedOfficeKeys = [];
            this.checkedOfficeKeys = [];
            this.expandedKeysMap = new Map();
            this.treeDataCheckedMap = new Map();
            this.halfCheckedKeysMap = new Map();
            this.autoExpandParent = true;
            this.editItem = {};
            this.dataScope = "1";
            const postData = {
                "page.current": 1,
                "page.size": 1000,
                isAll: true
            };
            adminMenu({ id: 9 }).then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    const childrenNav = [];
                    listToTree(data, childrenNav, 0);
                    console.log(childrenNav);
                    this.treeData = childrenNav;
                    if (this.treeData && this.treeData.length > 0) {
                        this.currentItemId = this.treeData[0].id;
                    }
                    console.log('this.treeData', this.treeData)
                }
            });
            this.editModal = true;
            this.form = this.$form.createForm(this, {
                mapPropsToFields: () => {
                    return {
                        roleName: this.$form.createFormField({
                            value: null
                        }),
                        remarks: this.$form.createFormField({
                            value: null
                        }),
                        roleSort: this.$form.createFormField({
                            value: null
                        }),
                        // roleType: this.$form.createFormField({
                        //     value: String(
                        //         this.editItem.roleType == null ? "" : this.editItem.roleType
                        //     )
                        // }),
                        // userType: this.$form.createFormField({
                        //     value: String(
                        //         this.editItem.userType == null ? "" : this.editItem.userType
                        //     )
                        // })
                    };
                }
            });
        },
        //删除
        deleteSysRole () {
            if (this.tableKeys.length != 1) {
                this.$message.warning('请选择一个角色');
                return;
            }
            let menu = this.tableRows[0];
            let _this = this;
            this.$confirm({
                title: '提示',
                content: '您确定要删除该角色吗？',
                onOk () {
                    deleteSysRole({ id: menu.id })
                        .then(response => {
                            if (response.code === 200) {
                                _this.$message.success("删除成功");
                                //刷新 列表
                                _this.PageListRole();
                                _this.tableRows = [];
                                _this.tableKeys = [];
                            }
                        });
                },
                onCancel () {
                },
            });
        },
        //停用/启用角色
        updateRole () {
            if (this.tableKeys.length != 1) {
                this.$message.warning('请选择一个角色');
                return;
            }
            let role = this.tableRows[0];

            let msg = role.status == 0 ? "停用" : "启用";
            let _this = this;
            this.$confirm({
                title: '提示',
                content: '您确定要' + msg + '该角色吗？',
                onOk () {
                    saveSysRole({
                        id: role.id,
                        status: role.status == 2 ? 0 : 2
                    })
                        .then(response => {
                            if (response.code === 200) {
                                _this.$message.success(msg + "成功");
                                //刷新 列表
                                _this.PageListRole();
                                _this.tableRows = [];
                                _this.tableKeys = [];
                            }
                        });
                },
                onCancel () {
                },
            });
        },
        // 获取角色列表
        PageListRole () {
            const { postData } = this;
            PageListRole(postData)
                .then(response => {
                    console.log("获取角色列表", response);
                    if (response.code === 200) {
                        const { data } = response;
                        const { records, total, current, size } = data;
                        this.data = records;
                        Object.assign(this.pagination, {
                            total
                        });
                    }
                })
                .catch(error => { });
        },
        //获取系统角色
        showFunction () {
            this.show = !this.show;
        },
        //编辑角色
        showModal () {
            if (this.tableKeys.length != 1) {
                this.$message.warning('请选择一个角色');
                return;
            }
            let editItem = this.tableRows[0];
            console.log("editItem", editItem);
            // this.expandedKeys = [];
            // this.checkedKeys = [];
            // this.halfCheckedKeys = [];
            this.expandedKeysMap = new Map();
            this.treeDataCheckedMap = new Map();
            this.halfCheckedKeysMap = new Map();
            this.editItem = { ...editItem };
            this.dataScope = String(editItem.dataScope);
            this.form = this.$form.createForm(this, {
                mapPropsToFields: () => {
                    return {
                        roleName: this.$form.createFormField({
                            value: this.editItem.roleName
                        }),
                        remarks: this.$form.createFormField({
                            value: this.editItem.remarks
                        }),
                        roleSort: this.$form.createFormField({
                            value: this.editItem.roleSort
                        }),
                        roleType: this.$form.createFormField({
                            value: String(
                                this.editItem.roleType == null ? "" : this.editItem.roleType
                            )
                        }),
                        userType: this.$form.createFormField({
                            value: String(
                                this.editItem.userType == null ? "" : this.editItem.userType
                            )
                        })
                    };
                }
            });
            const postData = {
                "page.current": 1,
                "page.size": 1000,
                isAll: true
            };
            adminMenu({ id: 9 }).then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    const childrenNav = [];
                    listToTree(data, childrenNav, 0);
                    this.treeData = childrenNav;
                    if (this.treeData && this.treeData.length > 0) {
                        this.currentItemId = this.treeData[0].id;
                    }
                    //获取授权菜单
                    MenuList({ id: this.editItem.id }).then(response => {
                        if (response.code === 200) {
                            const { data } = response;
                            console.log("用户角色菜单data", data);
                            //取第一级的ID
                            data.forEach(f => {
                                if (f.treeLevel === 0) {
                                    this.treeDataCheckedMap.set(f.id, []);
                                    this.expandedKeysMap.set(f.id, []);
                                    this.halfCheckedKeysMap.set(f.id, []);
                                }
                            })
                            this.treeDataCheckedMap.forEach((arr, key) => {
                                console.log("treeDataCheckedMap:key:", key, "arr", arr);
                                const halfCheckedKeys = this.halfCheckedKeysMap.get(key);
                                const expandedKeys = this.expandedKeysMap.get(key);
                                halfCheckedKeys.push(key);
                                expandedKeys.push(key);
                                data.forEach(item => {
                                    if ((item.parentIds + ",").indexOf("," + key + ",") > -1) {

                                        if (item.treeLeaf == 1) {
                                            // this.checkedKeys.push(item.id);
                                            arr.push(item.id);
                                        } else {
                                            // this.halfCheckedKeys.push(item.id);
                                            halfCheckedKeys.push(item.id);
                                            expandedKeys.push(item.id);
                                        }

                                    }
                                });
                            });
                            console.log("角色菜单赋值后的情况：", this.treeDataCheckedMap, this.halfCheckedKeysMap, this.expandedKeysMap);
                            this.autoExpandParent = false;
                            this.$forceUpdate();
                        }
                    });
                }
            });

            if (this.editItem.dataScope == 4 || this.editItem.dataScope == 5) {
                //获取授权机构
                OfficeList({
                    roleId: this.editItem.id,
                    type: this.editItem.dataScope == 4 ? "office" : "user"
                }).then(response => {
                    if (response.code === 200) {
                        const { data } = response;
                        console.log(data);
                        this.checkedOfficeKeys = data;
                    }
                });
            }

            this.editModal = true;
        },
        onTableChange (pagination, filters, sorter) {
            console.log("pagination", pagination);
            Object.assign(this.postData, {
                "page.current": pagination.current,
                "page.size": pagination.pageSize
            });
            Object.assign(this.pagination, {
                current: pagination.current,
                pageSize: pagination.pageSize
            });
            this.PageListRole();
        },
        onCellChange (item, dataIndex, editValue) {
            if (item[dataIndex] != editValue) {
                const edit = { id: item.id, [dataIndex]: editValue };
                this.TreeSortEditList.set(item.id, edit);
            } else {
                this.TreeSortEditList.delete(item.id);
            }
            console.log([...this.TreeSortEditList.values()]);
        },
        handleSubmit (e) {
            const { treeDataCheckedMap, halfCheckedKeysMap } = this;
            //角色保存提交
            e.preventDefault();
            this.form.validateFields((err, values) => {

                let id = this.editItem.id;
                this.editItem = { ...values };
                this.editItem.id = id;
                let menuIds = [];
                treeDataCheckedMap.forEach((value) => menuIds.push(...value));
                halfCheckedKeysMap.forEach((value) => menuIds.push(...value));

                this.editItem.menuId = menuIds;
                console.log("this.editItem.menuId ", menuIds);
                this.editItem.dataScope = this.dataScope;
                if (this.dataScope == "4") {
                    if (this.checkedOfficeKeys.length < 1) {
                        this.$message.warn("至少选择一个部门");
                        return;
                    }
                    this.editItem.officeId = this.checkedOfficeKeys;
                }
                if (this.dataScope == "5") {
                    if (this.checkedOfficeKeys.length < 1) {
                        this.$message.warn("至少选择一个人员");
                        return;
                    }
                    this.editItem.userId = this.checkedOfficeKeys;
                }

                console.log("开始保存:", this.editItem, this.dataScope);
                if (!err) {
                    saveSysRole(this.editItem)
                        .then(response => {
                            if (response.code === 200) {
                                this.$message.success("保存成功");
                                //刷新 列表
                                this.PageListRole();
                                this.hideModal();
                            }
                        })
                }
            });
        },
        //部门选择
        showOfficeModal (type) {
            this.officeModal = true;
            this.checkedOfficeKeys = [];
            this.expandedOfficeKeys = [];
            this.editItem.type = type;
            const postData = {
                "page.current": 1,
                "page.size": 1000,
                isLoadUser: type
            };
            //获取机构数据
            TreeDataOffice(postData).then(response => {
                console.log("获取机构列表", response.data);
                if (response.code === 200) {
                    const { data } = response;
                    const childrenOffice = [];
                    let keys = [];
                    for (let i = 0; i < data.length; i++) {
                        const node = data[i];
                        const key = node.id;
                        keys.push(key);
                    }
                    officeListToTree(response.data, childrenOffice, "0");
                    console.log("role---office", childrenOffice);
                    this.officeTreeData = childrenOffice;
                    //获取授权机构
                    OfficeList({
                        roleId: this.editItem.id,
                        type: this.editItem.dataScope == 4 ? "office" : "user"
                    }).then(response => {
                        if (response.code === 200) {
                            const { data } = response;
                            console.log(data);
                            this.checkedOfficeKeys = data;
                        }
                    });
                    this.expandedOfficeKeys = keys;
                }
            }).catch(error => { });
            
        },
        reset () {
            this.postData = {};
        },
        //自定义人员选择
        userModal () {
            this.$refs["user-modal"].show();
        },
        handleReset () {
            this.form.resetFields();
        },
        toggle () {
            this.expand = !this.expand;
        },
        //状态change
        handleChange (value) {
            this.postData.status = value;
            this.PageListRole();
        },
        //以下为dataTree 事件触发
        onExpand (expandedKeys) {
            console.log("onExpand方法：", expandedKeys);
            const { expandedKeysMap, currentItemId } = this;
            expandedKeysMap.set(currentItemId, expandedKeys);
            // this.expandedKeys = expandedKeys;

            this.$forceUpdate();
        },
        onCheck (checkedKeys, info) {
            console.log("onCheck方法：checkedKeys:", checkedKeys, "info:", info)

            const { treeDataCheckedMap, halfCheckedKeysMap, currentItemId } = this;
            treeDataCheckedMap.set(currentItemId, checkedKeys);
            halfCheckedKeysMap.set(currentItemId, info.halfCheckedKeys);
            // this.halfCheckedKeys = info.halfCheckedKeys
            // this.checkedKeys = checkedKeys;

            this.$forceUpdate();
        },
        onSelect (selectedKeys, info) {
            console.log("onSelect", info);
            this.selectedKeys = selectedKeys;
        },
        onOfficeExpand (expandedOfficeKeys) {
            console.log("onExpand", expandedOfficeKeys);
            this.expandedOfficeKeys = expandedOfficeKeys;
            this.autoExpandParent = false;
        },
        onOfficeCheck (checkedOfficeKeys) {
            console.log("onCheck", checkedOfficeKeys);
            this.checkedOfficeKeys = checkedOfficeKeys;
        },
        onOfficeSelect (selectedOfficeKeys, info) {
            console.log("onSelect", info);
            this.selectedOfficeKeys = selectedOfficeKeys;
        }
    }
};
</script>
<style  scoped>
    .btn-group-fa i {
        font-size: 4rem;
    }
    .btn-group-fa .ant-radio-button-wrapper {
        height: 8rem;
        width: 8rem;
        text-align: center;
        padding: 1rem;
    }
    .btn-group-fa .ant-radio-button-wrapper p {
        margin: 0 !important;
    }
    .form-inline label {
        justify-content: left !important;
    }
    .form-inline > .col {
        margin-bottom: 1.5rem !important;
    }
    .icons-list >>> .anticon {
        margin-right: 8px;
        font-size: 16px;
    }
    .ant-advanced-search-form {
        padding: 24px;
        background: #fbfbfb;
    }

    .ant-advanced-search-form .ant-form-item {
        display: flex;
        margin-bottom: 0px !important;
    }

    .ant-advanced-search-form .ant-form-item-control-wrapper {
        flex: 1;
    }

    #components-form-demo-advanced-search .ant-form {
        max-width: none;
    }
    #components-form-demo-advanced-search .search-result-list {
        margin-top: 16px;
        background-color: #fafafa;
        min-height: 200px;
        text-align: center;
        padding-top: 80px;
    }
</style>
<style lang="less">
    @import '~@/style/setting/inventory.less';
    .edit-class {
        .ant-modal-body {
            padding: 0px;
        }
    }
</style>